// 管理后台JavaScript代码

// API基础配置
const API_BASE = '../api/';

// 全局变量
let currentVerificationData = null;
let currentAdmin = null;
let userPermissions = [];

// 退出登录（放在顶部确保立即可用）
function logout() {
    console.log('logout function called'); // 调试信息
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('admin_token');
        localStorage.removeItem('admin_info');
        sessionStorage.removeItem('admin_token');
        sessionStorage.removeItem('admin_info');
        window.location.href = 'login.html';
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkLoginStatus();
    
    // 显示当前日期
    document.getElementById('currentDate').textContent = new Date().toLocaleDateString('zh-CN');
    
    // 设置默认查询日期为今天
    document.getElementById('reservationDate').value = new Date().toISOString().split('T')[0];
    
    // 设置回车键触发验证
    document.getElementById('verificationCode').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            verifyReservation();
        }
    });
    
    // 调试：确保logout函数已定义
    console.log('logout function defined:', typeof logout);
});

// 标签页切换
function showTab(tabName) {
    // 检查权限
    const tabElement = document.querySelector(`[onclick="showTab('${tabName}')"]`);
    const requiredPermission = tabElement?.getAttribute('data-permission');
    if (requiredPermission && !hasPermission(requiredPermission)) {
        showAlert('', '权限不足，无法访问此页面');
        return;
    }
    
    // 隐藏所有标签内容
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => content.classList.remove('active'));
    
    // 移除所有标签的激活状态
    const navTabs = document.querySelectorAll('.nav-tab');
    navTabs.forEach(tab => tab.classList.remove('active'));
    
    // 显示选中的标签内容
    document.getElementById(tabName).classList.add('active');
    
    // 激活对应的导航标签
    event.target.classList.add('active');
    
    // 根据标签页加载对应数据
    switch(tabName) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'reservations':
            // 预约管理页面不自动加载，需要用户选择日期
            break;
        case 'admin':
            loadAdmins();
            break;
        case 'roles':
            loadRoles();
            break;
        case 'logs':
            loadLogs();
            break;
    }
}

// API请求封装
async function apiRequest(endpoint, options = {}) {
    try {
        const token = getToken();
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            }
        };
        
        const response = await fetch(API_BASE + endpoint, {
            ...defaultOptions,
            ...options
        });
        
        if (response.status === 401) {
            // 未授权，跳转到登录页
            window.location.href = 'login.html';
            return;
        }
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('API请求失败:', error);
        throw error;
    }
}

// 获取Token
function getToken() {
    return localStorage.getItem('admin_token') || sessionStorage.getItem('admin_token');
}

// 检查登录状态
async function checkLoginStatus() {
    const token = getToken();
    if (!token) {
        window.location.href = 'login.html';
        return;
    }
    
    try {
        const response = await apiRequest('admin_auth.php?action=profile');
        if (response.code === 200) {
            currentAdmin = response.data;
            userPermissions = currentAdmin.permissions || [];
            updateAdminInfo();
            initializePermissions();
            initializeData();
        } else {
            window.location.href = 'login.html';
        }
    } catch (error) {
        console.error('验证登录状态失败:', error);
        window.location.href = 'login.html';
    }
}

// 更新管理员信息显示
function updateAdminInfo() {
    if (currentAdmin) {
        document.getElementById('adminInfo').textContent = 
            `${currentAdmin.real_name || currentAdmin.username} (${currentAdmin.role_display_name})`;
    }
}

// 初始化权限控制
function initializePermissions() {
    // 检查每个需要权限的元素
    const permissionElements = document.querySelectorAll('[data-permission]');
    permissionElements.forEach(element => {
        const requiredPermission = element.getAttribute('data-permission');
        if (!hasPermission(requiredPermission)) {
            element.style.display = 'none';
        } else {
            element.style.display = '';
        }
    });
}

// 检查权限
function hasPermission(permission) {
    return userPermissions.includes(permission);
}

// 初始化数据加载
function initializeData() {
    // 初始化加载数据
    loadDashboard();
    loadConfig();
    loadSchedule();
    loadTimeSlots();
    loadClosures();
    loadRecentCheckins();
    
    // 如果有管理员权限，加载管理员数据
    if (hasPermission('admin.view')) {
        loadAdmins();
    }
    if (hasPermission('roles.view')) {
        loadRoles();
        loadPermissions();
    }
}


// 显示警告信息
function showAlert(containerId, message, type = 'error') {
    const container = document.getElementById(containerId);
    container.innerHTML = `
        <div class="alert alert-${type === 'success' ? 'success' : 'error'}">
            ${message}
        </div>
    `;
    
    // 3秒后自动清除
    setTimeout(() => {
        container.innerHTML = '';
    }, 3000);
}

// 加载仪表板数据
async function loadDashboard() {
    try {
        const today = new Date().toISOString().split('T')[0];
        
        // 获取今日统计
        const statsResponse = await apiRequest(`verification.php?action=daily_statistics&date=${today}`);
        
        if (statsResponse.code === 200) {
            const { slot_stats, total_stats } = statsResponse.data;
            
            // 更新统计卡片
            document.getElementById('todayReserved').textContent = total_stats.total_reserved || 0;
            document.getElementById('todayCheckedIn').textContent = total_stats.total_checked_in || 0;
            
            // 计算剩余名额
            let totalAvailable = 0;
            slot_stats.forEach(slot => {
                totalAvailable += slot.available_count || 0;
            });
            document.getElementById('todayAvailable').textContent = totalAvailable;
            
            // 获取开馆状态
            const configResponse = await apiRequest('museum_config.php?action=get_config&config_key=museum_status');
            if (configResponse.code === 200) {
                const status = configResponse.data.value === 'open' ? '开馆' : '闭馆';
                document.getElementById('museumStatus').textContent = status;
            }
            
            // 更新时段统计表格
            updateSlotStatsTable(slot_stats);
        }
    } catch (error) {
        console.error('加载仪表板失败:', error);
        document.getElementById('todayReserved').textContent = '错误';
        document.getElementById('todayCheckedIn').textContent = '错误';
        document.getElementById('todayAvailable').textContent = '错误';
        document.getElementById('museumStatus').textContent = '错误';
    }
}

// 更新时段统计表格
function updateSlotStatsTable(stats) {
    const tbody = document.getElementById('slotStatsTable');
    
    if (!stats || stats.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="loading">今日无开放时段</td></tr>';
        return;
    }
    
    tbody.innerHTML = stats.map(slot => `
        <tr>
            <td>${slot.slot_name || '未知'}</td>
            <td>${slot.start_time || ''} - ${slot.end_time || ''}</td>
            <td>${slot.reserved_count || 0}</td>
            <td>${slot.checked_in_count || 0}</td>
            <td>${slot.max_visitors || 0}</td>
            <td>${slot.available_count || 0}</td>
        </tr>
    `).join('');
}

// 加载系统配置
async function loadConfig() {
    try {
        const response = await apiRequest('museum_config.php?action=get_config');
        
        if (response.code === 200) {
            const configs = response.data;
            
            // 填充表单
            if (configs.museum_status) {
                document.getElementById('museumStatusSelect').value = configs.museum_status.value;
            }
            if (configs.advance_booking_days) {
                document.getElementById('advanceBookingDays').value = configs.advance_booking_days.value;
            }
            if (configs.daily_max_visitors) {
                document.getElementById('dailyMaxVisitors').value = configs.daily_max_visitors.value;
            }
            if (configs.slot_max_visitors) {
                document.getElementById('slotMaxVisitors').value = configs.slot_max_visitors.value;
            }
        }
    } catch (error) {
        console.error('加载配置失败:', error);
        showAlert('configAlert', '加载配置失败：' + error.message);
    }
}

// 保存系统配置
async function saveConfig() {
    if (!hasPermission('config.edit')) {
        showAlert('configAlert', '权限不足，无法保存配置');
        return;
    }
    
    try {
        const configs = [
            {
                config_key: 'museum_status',
                config_value: document.getElementById('museumStatusSelect').value,
                config_type: 'string'
            },
            {
                config_key: 'advance_booking_days',
                config_value: document.getElementById('advanceBookingDays').value,
                config_type: 'number'
            },
            {
                config_key: 'daily_max_visitors',
                config_value: document.getElementById('dailyMaxVisitors').value,
                config_type: 'number'
            },
            {
                config_key: 'slot_max_visitors',
                config_value: document.getElementById('slotMaxVisitors').value,
                config_type: 'number'
            }
        ];
        
        // 逐个保存配置
        for (const config of configs) {
            await apiRequest('museum_config.php?action=update_config', {
                method: 'POST',
                body: JSON.stringify(config)
            });
        }
        
        showAlert('configAlert', '配置保存成功！', 'success');
        
    } catch (error) {
        console.error('保存配置失败:', error);
        showAlert('configAlert', '保存配置失败：' + error.message);
    }
}

// 加载开馆时间
async function loadSchedule() {
    try {
        const response = await apiRequest('museum_config.php?action=get_schedule');
        
        if (response.code === 200) {
            const schedules = response.data;
            const weekdays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            
            const tbody = document.getElementById('scheduleTable');
            tbody.innerHTML = schedules.map(schedule => `
                <tr>
                    <td>${weekdays[schedule.day_of_week] || schedule.day_of_week}</td>
                    <td>
                        <span class="status-badge ${schedule.is_open ? 'status-open' : 'status-closed'}">
                            ${schedule.is_open ? '开馆' : '闭馆'}
                        </span>
                    </td>
                    <td>${schedule.open_time || '-'}</td>
                    <td>${schedule.close_time || '-'}</td>
                    <td>${schedule.max_visitors || 0}</td>
                    <td>
                        <button class="btn btn-primary" onclick="editSchedule(${schedule.day_of_week})">编辑</button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (error) {
        console.error('加载开馆时间失败:', error);
        document.getElementById('scheduleTable').innerHTML = 
            '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

// 加载时段管理
async function loadTimeSlots() {
    try {
        const response = await apiRequest('museum_config.php?action=get_time_slots');
        
        if (response.code === 200) {
            const slots = response.data;
            
            const tbody = document.getElementById('timeslotsTable');
            tbody.innerHTML = slots.map(slot => `
                <tr>
                    <td>${slot.slot_name}</td>
                    <td>${slot.start_time}</td>
                    <td>${slot.end_time}</td>
                    <td>${slot.max_visitors}</td>
                    <td>
                        <span class="status-badge ${slot.is_active ? 'status-open' : 'status-closed'}">
                            ${slot.is_active ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-primary" onclick="editTimeSlot(${slot.id})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteTimeSlot(${slot.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (error) {
        console.error('加载时段管理失败:', error);
        document.getElementById('timeslotsTable').innerHTML = 
            '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

// 加载闭馆日期
async function loadClosures() {
    try {
        const response = await apiRequest('museum_config.php?action=get_closure_dates');
        
        if (response.code === 200) {
            const closures = response.data;
            
            const tbody = document.getElementById('closuresTable');
            tbody.innerHTML = closures.map(closure => `
                <tr>
                    <td>${closure.closure_date}</td>
                    <td>${closure.closure_type === 'yearly' ? '每年重复' : '单次生效'}</td>
                    <td>${closure.reason || '-'}</td>
                    <td>
                        <span class="status-badge ${closure.is_active ? 'status-open' : 'status-closed'}">
                            ${closure.is_active ? '生效' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-danger" onclick="deleteClosure(${closure.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (error) {
        console.error('加载闭馆日期失败:', error);
        document.getElementById('closuresTable').innerHTML = 
            '<tr><td colspan="5" class="loading">加载失败</td></tr>';
    }
}

// 加载预约列表
async function loadReservations() {
    const date = document.getElementById('reservationDate').value;
    if (!date) {
        showAlert('reservationsAlert', '请选择日期');
        return;
    }
    
    try {
        // 这里需要实现获取指定日期预约的API
        // 暂时显示加载状态
        document.getElementById('reservationsTable').innerHTML = 
            '<tr><td colspan="7" class="loading">加载中...</td></tr>';
        
        showAlert('reservationsAlert', '功能开发中...', 'success');
        
    } catch (error) {
        console.error('加载预约失败:', error);
        showAlert('reservationsAlert', '加载预约失败：' + error.message);
    }
}

// 验证预约码
async function verifyReservation() {
    const code = document.getElementById('verificationCode').value.trim();
    if (!code) {
        showAlert('verificationAlert', '请输入预约码');
        return;
    }
    
    try {
        const response = await apiRequest(`verification.php?action=verify_code&code=${code}`);
        
        if (response.code === 200) {
            currentVerificationData = response.data;
            displayVerificationResult(response.data);
            document.getElementById('checkInBtn').style.display = 'inline-block';
            showAlert('verificationAlert', '预约码验证成功！', 'success');
        } else {
            document.getElementById('verificationResult').style.display = 'none';
            document.getElementById('checkInBtn').style.display = 'none';
            showAlert('verificationAlert', response.message || '验证失败');
        }
    } catch (error) {
        console.error('验证预约码失败:', error);
        showAlert('verificationAlert', '验证请求失败：' + error.message);
    }
}

// 显示验证结果
function displayVerificationResult(data) {
    const resultDiv = document.getElementById('verificationResult');
    
    const companionsHtml = data.companions && data.companions.length > 0 
        ? `<p><strong>同伴信息：</strong></p>
           <ul>${data.companions.map(c => `<li>${c.name} (${c.relationship || '同伴'})</li>`).join('')}</ul>`
        : '';
    
    resultDiv.innerHTML = `
        <h4>预约信息</h4>
        <p><strong>预约码：</strong>${data.reservation_code}</p>
        <p><strong>参观者：</strong>${data.visitor_name}</p>
        <p><strong>联系电话：</strong>${data.visitor_phone}</p>
        <p><strong>参观日期：</strong>${data.visit_date}</p>
        <p><strong>参观时段：</strong>${data.slot_name || '全天'} (${data.start_time || ''} - ${data.end_time || ''})</p>
        <p><strong>参观人数：</strong>${data.visitor_count}人</p>
        ${companionsHtml}
        <p><strong>预约状态：</strong><span class="status-badge status-open">${data.status === 'confirmed' ? '已确认' : data.status}</span></p>
        ${data.check_in_time ? `<p><strong>签到时间：</strong>${data.check_in_time}</p>` : ''}
    `;
    
    resultDiv.style.display = 'block';
}

// 签到
async function checkInReservation() {
    if (!currentVerificationData) {
        showAlert('verificationAlert', '请先验证预约码');
        return;
    }
    
    try {
        const response = await apiRequest('verification.php?action=check_in', {
            method: 'POST',
            body: JSON.stringify({
                reservation_code: currentVerificationData.reservation_code,
                notes: '管理后台签到'
            })
        });
        
        if (response.code === 200) {
            showAlert('verificationAlert', '签到成功！', 'success');
            document.getElementById('verificationCode').value = '';
            document.getElementById('verificationResult').style.display = 'none';
            document.getElementById('checkInBtn').style.display = 'none';
            currentVerificationData = null;
            
            // 刷新最近签到记录
            loadRecentCheckins();
            
        } else {
            showAlert('verificationAlert', response.message || '签到失败');
        }
    } catch (error) {
        console.error('签到失败:', error);
        showAlert('verificationAlert', '签到请求失败：' + error.message);
    }
}

// 加载最近签到记录
async function loadRecentCheckins() {
    try {
        const today = new Date().toISOString().split('T')[0];
        const response = await apiRequest(`verification.php?action=recent_checkins&date=${today}&limit=10`);
        
        if (response.code === 200) {
            const checkins = response.data;
            
            const tbody = document.getElementById('recentCheckinsTable');
            if (checkins.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="loading">今日暂无签到记录</td></tr>';
            } else {
                tbody.innerHTML = checkins.map(checkin => `
                    <tr>
                        <td>${checkin.check_in_time}</td>
                        <td>${checkin.reservation_code}</td>
                        <td>${checkin.visitor_name}</td>
                        <td>${checkin.visitor_count}人</td>
                        <td>${checkin.slot_name || '全天'}</td>
                    </tr>
                `).join('');
            }
        }
    } catch (error) {
        console.error('加载签到记录失败:', error);
        document.getElementById('recentCheckinsTable').innerHTML = 
            '<tr><td colspan="5" class="loading">加载失败</td></tr>';
    }
}

// 模态框相关函数
function showAddTimeSlotModal() {
    document.getElementById('addTimeSlotModal').style.display = 'block';
}

function showAddClosureModal() {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法添加闭馆日期');
        return;
    }
    
    // 初始化月份日期选择器
    initializeMonthlyDayOptions();
    initializeYearlyDayOptions();
    
    document.getElementById('addClosureModal').style.display = 'block';
}

// 切换闭馆类型字段显示
function toggleClosureFields() {
    const closureType = document.getElementById('closureType').value;
    
    // 隐藏所有字段组
    document.getElementById('singleDateGroup').style.display = 'none';
    document.getElementById('dateRangeGroup').style.display = 'none';
    document.getElementById('weeklyGroup').style.display = 'none';
    document.getElementById('monthlyGroup').style.display = 'none';
    document.getElementById('yearlyGroup').style.display = 'none';
    
    // 显示对应的字段组
    switch(closureType) {
        case 'once':
            document.getElementById('singleDateGroup').style.display = 'block';
            break;
        case 'range':
            document.getElementById('dateRangeGroup').style.display = 'block';
            break;
        case 'weekly':
            document.getElementById('weeklyGroup').style.display = 'block';
            break;
        case 'monthly':
            document.getElementById('monthlyGroup').style.display = 'block';
            break;
        case 'yearly':
            document.getElementById('yearlyGroup').style.display = 'block';
            break;
    }
}

// 初始化月份日期选择器
function initializeMonthlyDayOptions() {
    const monthlyDay = document.getElementById('monthlyDay');
    monthlyDay.innerHTML = '<option value="">选择日期</option>';
    
    for (let i = 1; i <= 31; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i + '日';
        monthlyDay.appendChild(option);
    }
}

// 初始化年度日期选择器
function initializeYearlyDayOptions() {
    const yearlyDay = document.getElementById('yearlyDay');
    yearlyDay.innerHTML = '<option value="">选择日期</option>';
    
    for (let i = 1; i <= 31; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i + '日';
        yearlyDay.appendChild(option);
    }
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
    
    // 清空表单
    if (modalId === 'addTimeSlotModal') {
        document.getElementById('slotName').value = '';
        document.getElementById('startTime').value = '';
        document.getElementById('endTime').value = '';
        document.getElementById('maxVisitors').value = '50';
    } else if (modalId === 'addClosureModal') {
        document.getElementById('closureDate').value = '';
        document.getElementById('closureType').value = 'once';
        document.getElementById('closureReason').value = '';
    } else if (modalId === 'addAdminModal') {
        document.getElementById('adminUsername').value = '';
        document.getElementById('adminPassword').value = '';
        document.getElementById('adminRealName').value = '';
        document.getElementById('adminEmail').value = '';
        document.getElementById('adminRole').value = '';
    } else if (modalId === 'addRoleModal') {
        document.getElementById('roleName').value = '';
        document.getElementById('roleDisplayName').value = '';
        document.getElementById('roleDescription').value = '';
        const checkboxes = document.querySelectorAll('#permissionsCheckbox input[type="checkbox"]');
        checkboxes.forEach(cb => cb.checked = false);
    }
}

// 添加时段
async function addTimeSlot() {
    if (!hasPermission('timeslots.edit')) {
        showAlert('timeslotsAlert', '权限不足，无法添加时段');
        return;
    }
    
    const slotName = document.getElementById('slotName').value.trim();
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const maxVisitors = document.getElementById('maxVisitors').value;
    
    if (!slotName || !startTime || !endTime || !maxVisitors) {
        alert('请填写完整信息');
        return;
    }
    
    try {
        const response = await apiRequest('museum_config.php?action=add_time_slot', {
            method: 'POST',
            body: JSON.stringify({
                slot_name: slotName,
                start_time: startTime,
                end_time: endTime,
                max_visitors: parseInt(maxVisitors)
            })
        });
        
        if (response.code === 200) {
            showAlert('timeslotsAlert', '时段添加成功！', 'success');
            closeModal('addTimeSlotModal');
            loadTimeSlots();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加时段失败:', error);
        alert('添加时段失败：' + error.message);
    }
}

// 添加管理员
async function addAdmin() {
    const username = document.getElementById('adminUsername').value.trim();
    const password = document.getElementById('adminPassword').value;
    const realName = document.getElementById('adminRealName').value.trim();
    const email = document.getElementById('adminEmail').value.trim();
    const roleId = document.getElementById('adminRole').value;
    
    if (!username || !password || !roleId) {
        alert('请填写必要信息');
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=create_admin', {
            method: 'POST',
            body: JSON.stringify({
                username,
                password,
                real_name: realName,
                email,
                role_id: parseInt(roleId)
            })
        });
        
        if (response.code === 200) {
            showAlert('adminAlert', '管理员添加成功！', 'success');
            closeModal('addAdminModal');
            loadAdmins();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加管理员失败:', error);
        alert('添加管理员失败：' + error.message);
    }
}

// 添加角色
async function addRole() {
    const name = document.getElementById('roleName').value.trim();
    const displayName = document.getElementById('roleDisplayName').value.trim();
    const description = document.getElementById('roleDescription').value.trim();
    
    const selectedPermissions = [];
    const checkboxes = document.querySelectorAll('#permissionsCheckbox input[type="checkbox"]:checked');
    checkboxes.forEach(cb => selectedPermissions.push(cb.value));
    
    if (!name || !displayName) {
        alert('请填写角色名称和显示名称');
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=create_role', {
            method: 'POST',
            body: JSON.stringify({
                name,
                display_name: displayName,
                description,
                permissions: selectedPermissions
            })
        });
        
        if (response.code === 200) {
            showAlert('rolesAlert', '角色添加成功！', 'success');
            closeModal('addRoleModal');
            loadRoles();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加角色失败:', error);
        alert('添加角色失败：' + error.message);
    }
}

// 添加闭馆日期
async function addClosure() {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法添加闭馆日期');
        return;
    }
    
    const closureType = document.getElementById('closureType').value;
    const closureReason = document.getElementById('closureReason').value.trim();
    
    if (!closureReason) {
        alert('请填写闭馆原因');
        return;
    }
    
    let closureData = {
        closure_type: closureType,
        reason: closureReason
    };
    
    // 根据闭馆类型收集不同的数据
    switch(closureType) {
        case 'once':
            const closureDate = document.getElementById('closureDate').value;
            if (!closureDate) {
                alert('请选择闭馆日期');
                return;
            }
            closureData.closure_date = closureDate;
            break;
            
        case 'range':
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            if (!startDate || !endDate) {
                alert('请选择开始和结束日期');
                return;
            }
            if (startDate > endDate) {
                alert('开始日期不能晚于结束日期');
                return;
            }
            closureData.start_date = startDate;
            closureData.end_date = endDate;
            break;
            
        case 'weekly':
            const weekdays = [];
            document.querySelectorAll('input[name="weekdays"]:checked').forEach(cb => {
                weekdays.push(parseInt(cb.value));
            });
            if (weekdays.length === 0) {
                alert('请至少选择一个星期几');
                return;
            }
            closureData.weekdays = weekdays;
            break;
            
        case 'monthly':
            const monthlyDay = document.getElementById('monthlyDay').value;
            if (!monthlyDay) {
                alert('请选择每月闭馆日期');
                return;
            }
            closureData.monthly_day = parseInt(monthlyDay);
            break;
            
        case 'yearly':
            const yearlyMonth = document.getElementById('yearlyMonth').value;
            const yearlyDay = document.getElementById('yearlyDay').value;
            if (!yearlyMonth || !yearlyDay) {
                alert('请选择每年闭馆的月份和日期');
                return;
            }
            closureData.yearly_month = parseInt(yearlyMonth);
            closureData.yearly_day = parseInt(yearlyDay);
            break;
            
        default:
            alert('请选择闭馆类型');
            return;
    }
    
    try {
        const response = await apiRequest('museum_config.php?action=add_closure_rule', {
            method: 'POST',
            body: JSON.stringify(closureData)
        });
        
        if (response.code === 200) {
            showAlert('closuresAlert', '闭馆规则添加成功！', 'success');
            closeModal('addClosureModal');
            loadClosures();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加闭馆规则失败:', error);
        alert('添加闭馆规则失败：' + error.message);
    }
}

// 删除时段
async function deleteTimeSlot(id) {
    if (!hasPermission('timeslots.edit')) {
        showAlert('timeslotsAlert', '权限不足，无法删除时段');
        return;
    }
    
    if (!confirm('确定要删除这个时段吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=delete_time_slot&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('timeslotsAlert', '时段删除成功！', 'success');
            loadTimeSlots();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除时段失败:', error);
        alert('删除时段失败：' + error.message);
    }
}

// 删除管理员
async function deleteAdmin(id) {
    if (!hasPermission('admin.edit')) {
        showAlert('adminAlert', '权限不足，无法删除管理员');
        return;
    }
    
    if (!confirm('确定要删除这个管理员吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`admin_management.php?action=delete_admin&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('adminAlert', '管理员删除成功！', 'success');
            loadAdmins();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除管理员失败:', error);
        alert('删除管理员失败：' + error.message);
    }
}

// 删除角色
async function deleteRole(id) {
    if (!hasPermission('roles.edit')) {
        showAlert('rolesAlert', '权限不足，无法删除角色');
        return;
    }
    
    if (!confirm('确定要删除这个角色吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`admin_management.php?action=delete_role&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('rolesAlert', '角色删除成功！', 'success');
            loadRoles();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除角色失败:', error);
        alert('删除角色失败：' + error.message);
    }
}

// 编辑管理员（占位函数）
function editAdmin(id) {
    alert('编辑管理员功能开发中...');
}

// 编辑角色（占位函数）
function editRole(id) {
    alert('编辑角色功能开发中...');
}

// 删除闭馆日期
async function deleteClosure(id) {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法删除闭馆日期');
        return;
    }
    
    if (!confirm('确定要删除这个闭馆日期吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=delete_closure_date&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('closuresAlert', '闭馆日期删除成功！', 'success');
            loadClosures();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除闭馆日期失败:', error);
        alert('删除闭馆日期失败：' + error.message);
    }
}

// 管理员管理功能
async function loadAdmins() {
    try {
        const response = await apiRequest('admin_management.php?action=admins');
        if (response.code === 200) {
            const admins = response.data.data;
            const tbody = document.getElementById('adminTable');
            tbody.innerHTML = admins.map(admin => `
                <tr>
                    <td>${admin.username}</td>
                    <td>${admin.real_name || '-'}</td>
                    <td>${admin.email || '-'}</td>
                    <td>${admin.role_display_name || '-'}</td>
                    <td><span class="status-badge ${admin.status === 'active' ? 'status-open' : 'status-closed'}">${admin.status === 'active' ? '正常' : '禁用'}</span></td>
                    <td>${admin.last_login_time || '从未登录'}</td>
                    <td>
                        <button class="btn btn-primary" onclick="editAdmin(${admin.id})" data-permission="admin.edit">编辑</button>
                        <button class="btn btn-danger" onclick="deleteAdmin(${admin.id})" data-permission="admin.edit">删除</button>
                    </td>
                </tr>
            `).join('');
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载管理员失败:', error);
        document.getElementById('adminTable').innerHTML = '<tr><td colspan="7" class="loading">加载失败</td></tr>';
    }
}

async function loadRoles() {
    try {
        const response = await apiRequest('admin_management.php?action=roles');
        if (response.code === 200) {
            const roles = response.data;
            const tbody = document.getElementById('rolesTable');
            tbody.innerHTML = roles.map(role => `
                <tr>
                    <td>${role.name}</td>
                    <td>${role.display_name}</td>
                    <td>${role.description || '-'}</td>
                    <td>${role.user_count || 0}</td>
                    <td><span class="status-badge ${role.status === 'active' ? 'status-open' : 'status-closed'}">${role.status === 'active' ? '启用' : '禁用'}</span></td>
                    <td>
                        <button class="btn btn-primary" onclick="editRole(${role.id})" data-permission="roles.edit">编辑</button>
                        ${!role.is_system ? `<button class="btn btn-danger" onclick="deleteRole(${role.id})" data-permission="roles.edit">删除</button>` : ''}
                    </td>
                </tr>
            `).join('');
            
            // 更新角色选择框
            const roleSelect = document.getElementById('adminRole');
            roleSelect.innerHTML = '<option value="">选择角色</option>' + 
                roles.filter(role => role.status === 'active').map(role => 
                    `<option value="${role.id}">${role.display_name}</option>`
                ).join('');
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载角色失败:', error);
        document.getElementById('rolesTable').innerHTML = '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

async function loadPermissions() {
    try {
        const response = await apiRequest('admin_management.php?action=permissions');
        if (response.code === 200) {
            const permissions = response.data;
            const container = document.getElementById('permissionsCheckbox');
            
            let html = '';
            for (const [module, perms] of Object.entries(permissions)) {
                html += `<h4>${module}</h4>`;
                html += perms.map(perm => `
                    <label style="display: block; margin-bottom: 0.5rem;">
                        <input type="checkbox" name="permissions" value="${perm.name}" style="margin-right: 0.5rem;">
                        ${perm.display_name} (${perm.description})
                    </label>
                `).join('');
            }
            container.innerHTML = html;
        }
    } catch (error) {
        console.error('加载权限失败:', error);
    }
}

async function loadLogs() {
    const logType = document.getElementById('logType').value;
    try {
        const action = logType === 'login' ? 'login_logs' : 'operation_logs';
        const response = await apiRequest(`admin_management.php?action=${action}`);
        
        if (response.code === 200) {
            const logs = response.data;
            const tbody = document.getElementById('logsTable');
            
            if (logType === 'login') {
                tbody.innerHTML = logs.map(log => `
                    <tr>
                        <td>${log.created_at}</td>
                        <td>${log.username}</td>
                        <td><span class="status-badge ${log.login_status === 'success' ? 'status-open' : 'status-closed'}">${log.login_status === 'success' ? '成功' : '失败'}</span></td>
                        <td>${log.ip_address}</td>
                        <td>${log.failure_reason || '正常登录'}</td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = logs.map(log => `
                    <tr>
                        <td>${log.created_at}</td>
                        <td>${log.username}</td>
                        <td>${log.action}</td>
                        <td>${log.ip_address}</td>
                        <td>${log.description}</td>
                    </tr>
                `).join('');
            }
        }
    } catch (error) {
        console.error('加载日志失败:', error);
        document.getElementById('logsTable').innerHTML = '<tr><td colspan="5" class="loading">加载失败</td></tr>';
    }
}

// 模态框管理
function showAddAdminModal() {
    if (!hasPermission('admin.edit')) {
        showAlert('adminAlert', '权限不足，无法添加管理员');
        return;
    }
    document.getElementById('addAdminModal').style.display = 'block';
}

function showAddRoleModal() {
    if (!hasPermission('roles.edit')) {
        showAlert('rolesAlert', '权限不足，无法添加角色');
        return;
    }
    loadPermissions();
    document.getElementById('addRoleModal').style.display = 'block';
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
}